package com.pxdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.pxdp.dto.Result;
import com.pxdp.entity.Shop;
import com.pxdp.mapper.ShopMapper;
import com.pxdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxdp.utils.CacheClient;
import com.pxdp.utils.RedisConstants;
import com.pxdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 从redis中查询店铺信息
     *
     * @param id
     * @return
     */
    @Override
    public Result cacheGetById(Long id) {
        //调用解决缓存穿透的方法
        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY,id,Shop.class,ids->getById(ids),RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);

        //调用互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);

        //逻辑过期解决缓存击穿问题

        if (BeanUtil.isEmpty(shop)) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }


    /**
     * 封装缓存穿透的解决方法
     *
     * @return
     */
    public Shop queryWithPassThrough(Long id) {
        //判断redis中是否有数据
        String jsonShop = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //如果存在直接返回数据
        if (!StrUtil.isBlank(jsonShop)) {
            Shop sp = JSONUtil.toBean(jsonShop, Shop.class);
            log.info("查询到redis数据返回");
            return sp;
        }
        //如果查询到空值直接返回错误信息
        if (jsonShop != null) {
            log.info("查询到不存在的店铺 返回空值");
            return null;
        }
        //如果不存在
        //查询数据库是否有数据
        Shop shop = getById(id);
        //判断查询到是否有数据
        if (BeanUtil.isEmpty(shop)) {
            //将空的值写入redis
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //有数据将数据添加到数据库并返回
        String jshop = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, jshop, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        log.info("查询到数据库数据返回");
        return shop;
    }

    /**
     * 解决缓存击穿问题的方法
     *
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id) {
        //判断redis中是否有数据
        String jsonShop = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //如果存在直接返回数据
        if (!StrUtil.isBlank(jsonShop)) {
            Shop sp = JSONUtil.toBean(jsonShop, Shop.class);
            log.info("查询到redis数据返回");
            return sp;
        }
        //如果查询到空值直接返回错误信息
        if (jsonShop != null) {
            log.info("查询到不存在的店铺 返回空值");
            return null;
        }
        Shop shop = null;

        try {
            //实现缓存重建
            //获取互斥锁
            //判断是否获取成功
            boolean flag = getLock(RedisConstants.LOCK_SHOP_KEY);
            if (!flag) {
                //获取失败，让线程休眠，之后在重新获取
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //获取成功 重新执行之前的查询redis的操作
            String rejsonShop = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
            //如果存在直接返回数据
            if (!StrUtil.isBlank(rejsonShop)) {
                Shop sp = JSONUtil.toBean(jsonShop, Shop.class);
                log.info("查询到redis数据返回");
                return sp;
            }
            //如果查询到空值直接返回错误信息
            if (rejsonShop != null) {
                log.info("查询到不存在的店铺 返回空值");
                return null;
            }

            //获取成功
            //如果不存在
            //查询数据库是否有数据
            shop = getById(id);
            //判断查询到是否有数据
            if (BeanUtil.isEmpty(shop)) {
                //将空的值写入redis
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //有数据将数据添加到数据库并返回
            String jshop = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, jshop, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            log.info("查询到数据库数据返回");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            reLock(RedisConstants.LOCK_SHOP_KEY);
        }

        return shop;
    }

    /**
     * 逻辑过期解决缓存击穿问题
     */
    public Shop queryWithLogicalExpire(Long id) {
        //判断redis中是否有数据
        String jsonShop = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        //如果不存在直接返回null
        if (StrUtil.isBlank(jsonShop)) {
            return null;
        }
        //存在，需要把json反序列化
        RedisData data = BeanUtil.toBean(jsonShop, RedisData.class);
        Shop shopData = JSONUtil.toBean((JSONObject) data.getData(), Shop.class);
        LocalDateTime expireTime = data.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期，直接返回店铺信息
            return shopData;
        }
        //过期，需要缓存重建
        //获取互斥锁
        boolean flag = getLock(RedisConstants.LOCK_SHOP_KEY + id);
        //判断是否获取锁成功
        if(flag){
            //获取成功开启独立线程,实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() ->{
                try {
                    this.saveShopToRedis(id,20L);

                } finally {
                    //释放锁
                    reLock(RedisConstants.LOCK_SHOP_KEY+id);
                }
            });
        }


        return shopData;
    }

    /**
     * 获取锁的方法
     *
     * @param key
     * @return
     */
    private boolean getLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁的方法
     *
     * @param key
     */
    private void reLock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 存储店铺信息和逻辑过期时间的方法
     */
    public void saveShopToRedis(Long id, Long expireSeconds) {
        //查询店铺信息
        Shop shop = getById(id);
        //将店铺信息封装到redisdata类
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        //将封装的类写入redis中
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 更新数据库并删除缓存
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result delete(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺不存在");
        }
        updateById(shop);

        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);

        return Result.ok();
    }
}
